<?php
/**
 * 购买管理
 */
defined('BASEPATH') OR exit("No direct script access allowed");

class BuyMan extends CI_Controller{

	//构造初始化函数
	public function __construct(){
		parent::__construct();

		//加载数据库
		$this->load->database();

		// //加载admin模型
		$this->load->model('admin/Buy_model','Buy');

		$this->load->model('admin/Patient_model','patient');
		$this->load->model('admin/LogAll_model','logAll');
		//加载表单验证规则
		$this->load->library('form_validation');

		$this->checkLogStatus();
	}

		/*
	 * 检查登陆状态
	 */
	public function checkLogStatus()
	{
		if (!$this->session->userdata('admin')){
			redirect('admin/Login');
		}

		echo "<script>alert("dfafadsfasfsf")</script>";
	}

	public function index(){

		$data['buInfo']=$this->Buy->getBuyAll();

		//print_r($data);
		$this->load->view("admin/Buy.html",$data);
	}


	public function testexcel(){




		exit();
		require "assets/PHPExcel/PHPExcel.php";
		//创建对象
		$excel = new PHPExcel();
		//Excel表格式,这里简略写了8列
		//$letter = array('A','B','C','D','E','F','G','H','I','J','K');
		$letter = array('A','B','C','D','E','F','F','G');
		$tableheader = array('学号','姓名','性别','年龄','班级');
		for($i = 0;$i < count($tableheader);$i++) {
			$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
		}
		//表格数组

		$data = array(

		array('1','小王','男','20','100'),

		array('2','小李','男','20','101'),

		array('3','小张','女','20','102'),

		array('4','小赵','女','20','103')

		);


		for ($i = 2;$i <= count($data) + 1;$i++) {

			$j = 0;

			foreach ($data[$i - 2] as $key=>$value) {

			$excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");

			$j++;

			}
		}
			$write = new PHPExcel_Writer_Excel5($excel);

			header("Pragma: public");

			header("Expires: 0");

			header("Cache-Control:must-revalidate, post-check=0, pre-check=0");

			header("Content-Type:application/force-download");

			header("Content-Type:application/vnd.ms-execl");

			header("Content-Type:application/octet-stream");

			header("Content-Type:application/download");;

			header('Content-Disposition:attachment;filename="testdata.xls"');

			header("Content-Transfer-Encoding:binary");

			$write->save('php://output');

	}


	public function upload(){

		if(is_uploaded_file($_FILES['upload_file1']['tmp_name'])){

						$count=0;

						$first_file = $_FILES['upload_file1'];  //获取文件1的信息

						if ($first_file['error'] == UPLOAD_ERR_OK){

					    $temp_name = $first_file['tmp_name'];

					    $file_name = $first_file['name'];

					    $type=$first_file["type"];//上传文件的类型

					  	if($type!="application/vnd.ms-excel")
					  	{
					  		echo "type no xls";
					  		exit();
					  	}

					  	//文件时间戳
					  	$timecuo=time();
					    //移动临时文件夹中的文件1到存放上传文件的目录，并重命名为真实名称
					    $aa="./assets/upload/".$timecuo.$file_name;
					    // echo base_url();
						move_uploaded_file($temp_name, $aa);
					    
						//开始分析xls
						require "assets/PHPExcel/PHPExcel.php";

					    require 'assets/PHPExcel/PHPExcel/IOFactory.php';

					    require 'assets/PHPExcel/PHPExcel/Reader/Excel5.php';

					    $objReader = PHPExcel_IOFactory::createReader('Excel5'); //use Excel5 for 2003 format 

					    $excelpath=$aa;

					    $objPHPExcel = $objReader->load($excelpath); 

					    $sheet = $objPHPExcel->getSheet(0); 

					    $highestRow = $sheet->getHighestRow();           //取得总行数 

						$highestColumn = "I"; //取得总列数
					    for($j=3;$j<=$highestRow;$j++)                        //从第二行开始读取数据
					  	 { 
					  	 		$count++;
							    $str="";

						        for($k='A';$k<=$highestColumn;$k++)            //从A列读取数据

						         { 

						             $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'|*|';//读取单元格

						         } 

								$str=mb_convert_encoding($str,'utf-8','auto');//根据自己编码修改

								$strs = explode("|*|",$str);
								// header('Content-Type:text/html;charset=gbk');
								// echo '<pre>';
								//print_r($strs);
								
								//开始注入信息
								$data['name']=$strs[0];
								$data['mobil']=$strs[1];
								$data['timeb']=$this->excelTime($strs[2]);
								$data['address']=$strs[3];
								$data['product']=$strs[4];
								$data['oprice']=$strs[5];
								$data['number']=$strs[6];
								$data['aprice']=$strs[7];
								$data['beizhu']=$strs[8];

								//检索是哪个医生下的
								$hah=$this->patient->getPatientByMobile($data['mobil']);

								if(empty($hah)){

								}else{
									$data['doctorid']=$hah["doctorid"];
								}
								
								if($this->Buy->addBuyRecord($data)){
									  	//成功就什么都不做
									}else{
									  	//失败那么就记录一个
									  	//$error='';
									}	
								
						}

							$logData["operation"]="在购买管理中批量导入了".$count.'条数据';
							$logData["timeb"]='20'.date("y-m-d",time());
							$logData["person"]=$this->session->userdata('admin');
							$this->logAll->addOne($logData);	

						$a=base_url("assets/error/sccg.html");
						header("Location: $a"); 
				  		exit();
					}else{
					    $a=base_url("assets/error/scsb.html");
					    header("Location: $a"); 
	  					exit();
					}
	  		}else{
	  				//echo '<script>alert("文件格式不对")</script>';
	  				$a=base_url("assets/error/wjerror.html");
	  				header("Location: $a"); 
	  				exit();
	  		}
	}

	//添加单条信息
	public function addBuyRecordOne(){

		$data['name']=$this->input->post('addNameid',TRUE);
		$data['mobil']=$this->input->post('addMobileid',TRUE);
		$data['address']=$this->input->post('addAddressid',TRUE);
		$data['product']=$this->input->post('addProuctid',TRUE);
		$data['oprice']=$this->input->post('addOpriceid',TRUE);
		$data['number']=$this->input->post('addnumberid',TRUE);
		$data['aprice']=$this->input->post('addApriceid',TRUE);
		$data['timeb']=$this->input->post('addBuyTimeid',TRUE);
		$data['beizhu']=$this->input->post('addBeizhu',TRUE);

		//检索是哪个医生下的
		$hah=$this->patient->getPatientByMobile($data['mobil']);

		if(empty($hah)){

		}else{
			$data['doctorid']=$hah["doctorid"];
		}
		
	 	if($this->Buy->addBuyRecord($data)){

	 		$logData["operation"]="在购买管理中单个添加了一条数据";
			$logData["timeb"]='20'.date("y-m-d",time());
			$logData["person"]=$this->session->userdata('admin');
			$this->logAll->addOne($logData);	

		  	echo 1;
		}else{
		  	echo 0;
		}
	}

	//编辑一条记录
	public function editorOneDoc($id=1){
		 $data['DoctorOne']=$this->Buy->getDoctorOne($id);
		 //print_r($data['DoctorOne']);
		 $this->load->view("admin/BuyEditor.html",$data);
	}

	/*
	 * 更新一条数据
	 */
	public function updateGroupOne($id=1){
		$data['name']=$this->input->post('name',TRUE);
		$data['mobil']=$this->input->post('mobil',TRUE);
		$data['timeb']=$this->input->post('timeb',TRUE);
		$data['address']=$this->input->post('address',TRUE);
		$data['product']=$this->input->post('product',TRUE);
		$data['oprice']=$this->input->post('oprice',TRUE);
		$data['number']=$this->input->post('number',TRUE);
		$data['aprice']=$this->input->post('aprice',TRUE);
		$data['beizhu']=$this->input->post('beizhu',TRUE);

		//这里要先检索出所属医生才行===》
		//检索是哪个医生下的
		$hah=$this->patient->getPatientByMobile($data['mobil']);

		if(empty($hah)){

		}else{
			$data['doctorid']=$hah["doctorid"];
		}

		if($this->Buy->updateOne($id,$data)){

			$logData["operation"]="在购买管理中更新了一条数据，数据id是".$id;
			$logData["timeb"]='20'.date("y-m-d",time());
			$logData["person"]=$this->session->userdata('admin');
			$this->logAll->addOne($logData);

			redirect("admin/BuyMan/index");
		} 
		else {
			echo '修改错误，请联系开发员查看问题';
		}
		
	}

	//测试之用
	public function test()
	{
		   // echo base_url("assets/PHPExcel/PHPExcel.php");
			require "assets/PHPExcel/PHPExcel.php";

		    require 'assets/PHPExcel/PHPExcel/IOFactory.php';

		    require 'assets/PHPExcel/PHPExcel/Reader/Excel5.php';

		    $objReader = PHPExcel_IOFactory::createReader('Excel5'); //use Excel5 for 2003 format 

		    $excelpath='buy.xls';

		    $objPHPExcel = $objReader->load($excelpath); 

		    $sheet = $objPHPExcel->getSheet(0); 

		    $highestRow = $sheet->getHighestRow();           //取得总行数 

			$highestColumn = $sheet->getHighestColumn(); //取得总列数

			echo $highestColumn;

			//echo base_url("assets/PHPExcel/PHPExcel.php");
	}

	//删除一条记录 
	public function deleteOne()
	{
		//设置验证规则
		$this->form_validation->set_rules('DoctorId','参数','required');
		 //先验证规则
		if($this->form_validation->run()==false){
			echo validation_errors();
			exit();
		}
		$data['id']=$this->input->post('DoctorId',TRUE);
		if($this->Buy->deleteDoctorOne($data['id']))
		{
			$logData["operation"]="在购买管理中删除了一条数据，医生id是".$data['id'];
			$logData["timeb"]='20'.date("y-m-d",time());
			$logData["person"]=$this->session->userdata('admin');
			$this->logAll->addOne($logData);

			echo 1;
		}else{
			echo 0;
		}
	}

	public function excelTime($date, $time = false) {

		    if(function_exists('GregorianToJD')){

		        if (is_numeric( $date )) {

		        $jd = GregorianToJD( 1, 1, 1970 );

		        $gregorian = JDToGregorian( $jd + intval ( $date ) - 25569 );

		        $date = explode( '/', $gregorian );

		        $date_str = str_pad( $date [2], 4, '0', STR_PAD_LEFT )

		        ."-". str_pad( $date [0], 2, '0', STR_PAD_LEFT )

		        ."-". str_pad( $date [1], 2, '0', STR_PAD_LEFT )

		        . ($time ? " 00:00:00" : '');

		        return $date_str;
		        }

		    }else{

		       // $date=$date>25568? $date+1:25569;

		        /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/

		        $ofs=(70 * 365 + 17+2) * 86400;

		        $date = date("Y-m-d",($date * 86400) - $ofs).($time ? " 00:00:00" : '');
		        return $date;
		    }

	}

	public function Pasearch(){
		$name=$this->input->get('info',TRUE);
		$data['buInfo']=$this->Buy->getDoByName($name);
		$this->load->view("admin/Buy.html",$data);
	}

	public function Mosearch(){
		$name=$this->input->get('info',TRUE);
		$data['buInfo']=$this->Buy->getDoByMobile($name);
		$this->load->view("admin/Buy.html",$data);
	}

	public function Dnsearch(){
		$name=$this->input->get('info',TRUE);
		$data['buInfo']=$this->Buy->getDoByDoctorN($name);
		$this->load->view("admin/Buy.html",$data);
	}

	public function Tisearch(){
		$time=$this->input->get('info',TRUE);
		$startTime=substr($time,6,4).'-'.substr($time,0,2).'-'.substr($time,3,2);
		$endTime=substr($time,19,4 ).'-'.substr($time, 13,2).'-'.substr($time,16,2);
		$data['buInfo']=$this->Buy->getDoByTime($startTime,$endTime);
		$this->load->view("admin/Buy.html",$data);
	}
}
